package com.bbcare.mqservice.controller;


import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bbcare.mqservice.entity.Ipconfig;
import com.bbcare.mqservice.entity.Message;
import com.bbcare.mqservice.pojo.ResultModel;
import com.bbcare.mqservice.service.IIpconfigService;
import com.bbcare.mqservice.service.IMessageService;
import com.bbcare.mqservice.utils.HttpUtil;
import com.bbcare.mqservice.utils.IpUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.xml.crypto.Data;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 小程序转发服务
 */
@Controller
@RequestMapping("/switchData")
public class queryController {


    private static final Logger log = LogManager.getLogger();
    @Autowired
    private IIpconfigService ipconfigService;
    @Autowired
    private IMessageService iMessageService;

    @ResponseBody
    @RequestMapping(value = "/**")
    public String doSwitch(@RequestBody String requestBody, HttpServletRequest request) {

        JSONObject jsonObject = JSON.parseObject(requestBody);
        String deptId = jsonObject.getJSONObject("data").getString("deptId");
        Message message = new Message();
        message.setOriIp(IpUtils.getIpAddr(request));
        message.setCreatTime(LocalDateTime.now());
        String result = "fail";
        message.setMessage(requestBody);
        message.setType("查询");
        String ip = ipconfigService.getIpByDeptId(deptId);

        if (ip != null) {
            message.setEndIp(ip + request.getRequestURI());
            try {
                String params = request.getRequestURI().replace("dataSwitch", "followup");
                result = HttpUtil.postData(ip + params, requestBody);
            } catch (Exception ex) {
                result = ex.getMessage();
                message.setEndTime(LocalDateTime.now());
                iMessageService.save(message);
            } finally {
                //log.info("2:"+LocalDateTime.now());
                if (result.length() < 100)
                    log.info("请求：" + requestBody + "结果:" + result);
            }

        } else {
            log.info(deptId + "deptId没有配置相应的ip");
            result = deptId + "没有配置相应的ip";
            iMessageService.save(message);
        }

        return result;

    }

}
